import React, { PureComponent } from 'react';
// 引入详情页样式
import './scss/details.scss';
// 引入请求
import Axios from 'axios';
// 引入地址
import { webSite } from '../../website';
// 引入框架
import { message } from 'antd';
// 引入仓库
import store from '../../store/index';
export default class Details extends PureComponent {
  constructor() {
    super()
    this.state = {
      // 存储小说数据
      novelObj: {},
      // 小说章节
      novelFont: []
    }
    // state的写法
    this.unSubscribe = store.subscribe(() => {
      // 强制更新
      this.forceUpdate()
    })
  }
  componentWillUnmount () {
    this.unSubscribe()
    // 卸载异步操作设置状态
    this.setState = () => {
      return;
    }
  }
  componentDidMount () {
    // 网页加载数据赋值给对象
    this.setState({
      novelObj: this.props.location.state
    }, () => {
      // 小说章节
      Axios.create({
        baseURL: `${webSite}:3003`
      }).post("/getnovelFont", { novelUrl: this.props.location.state.novelHref }).then(err => {
        if (err.data.code === 'F0001') {
          this.setState({
            novelFont: err.data.novelFontAll
          })
        }
      }).catch(() => {
        message.error({ content: '网络错误', className: 'bulletChatMessage' });
      })
    })
  }
  // 退回主页
  escHome = () => {
    this.props.history.replace('/novel');
  }
  // 跳转到阅读页面
  goReader = (Font, index) => {
    let { novelFont } = this.state;
    if (novelFont.length === 0) {
      message.error({ content: '请先获取章节内容才能阅读', className: 'bulletChatMessage' });
      return;
    }
    this.props.history.push({ pathname: "/novel/Reader", state: { Font, index, novelHref: this.props.location.state.novelHref } });
  }
  // 添加到服务器
  goBox = () => {
    let { userId } = store.getState().reducer;
    let { novelObj, novelFont } = this.state;
    // 防止没有章节时存到目录
    if (novelObj.novelHref === undefined) {
      this.props.history.replace('/');
      return;
    }
    if (!userId) {
      // 用户没有登录跳转到首页
      this.props.history.replace('/')
      return;
    }
    // 必须有章节
    if (novelFont.length === 0) {
      message.success({ content: '章节加载完成才能添加到书架', className: 'bulletChatMessage' });
      return;
    }
    // 获取番剧名字
    let text = document.getElementById('novelTextID');
    // 去掉名字里的所有空格
    let novelText = (text.textContent).replace(/\s+/g, "");
    // 获取番剧作者
    let author = document.getElementById('novelAuthorID');
    // 去掉作者里面的所有空格
    let novelAuthor = (author.textContent).replace(/\s+/g, "");
    // 创建一个电子书的专属对象
    let getNovelObj = {};
    getNovelObj = {
      // 每个书一个id
      id: Math.ceil(Math.random() * 10000000000),
      // 封面
      novelImg: novelObj.novelImg,
      // 名字
      novelText,
      // 作者
      novelAuthor,
      // 第几集链接
      novelUrl: novelFont[0].novelUrl,
      // 总集数
      novellang: novelFont.length,
      // 书签
      bookmark: [],
      // 第几集 
      index: 1,
      // 总集数链接
      novelHref: this.props.location.state.novelHref
    }
    // 把章节内容写入服务器
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/setNovel", { id: userId, Novel: getNovelObj }).then(err => {
      // 添加成功
      if (err.data.code === 'N0001') {
        message.success({ content: '加入书架成功', className: 'bulletChatMessage' });
        return;
        // 防止重复添加
      } else if (err.data.code === 'N0002') {
        message.success({ content: '已添加到书架，请勿重复添加', className: 'bulletChatMessage' });
        return;
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }
  render () {
    let { novelObj, novelFont } = this.state;
    return (
      <div className='details'>
        {/* 顶部 */}
        <div className='details_title'>
          <div className='details_title_body'>
            <h3 dangerouslySetInnerHTML={{ __html: novelObj.novelText }} id='novelTextID'></h3>
            <span dangerouslySetInnerHTML={{ __html: novelObj.novelAuthor }} id='novelAuthorID'></span>
          </div>
          <div className='details_title_body_img'>
            <img src={novelObj.novelImg} alt="封面" width='100' />
          </div>
        </div>
        {/* 内容介绍 */}
        <div className='details_const'>
          <div className='details_const_img'>
            <img src={require('./image/shu.png')} alt="书" width='60' />
          </div>
          <div className='details_const_body' dangerouslySetInnerHTML={{ __html: novelObj.novelMedium }}></div>
        </div>
        {/* 集数介绍 */}
        <ul className='details_body'>
          {
            novelFont.length !== 0 ?
              novelFont.map((list, index) => {
                return (
                  <li className='details_body_li' key={index} dangerouslySetInnerHTML={{ __html: list.novelText }} onClick={() => this.goReader(novelFont[index], index)}></li>
                )
              })
              : <li style={{ color: '#999' }}>章节加载中....</li>
          }
        </ul>
        {/* 底部加入书架 */}
        <div className='details_bottom'>
          <div className='details_bottom_add'>
            <img src={require('../image/shujia.png')} alt="加入书架" width='22' onClick={this.goBox} />
            <p>加入书架</p>
          </div>
          <div className='details_bottom_add' style={{ background: 'rgb(230, 85, 77)' }} onClick={() => this.goReader(novelFont[0], 0)}>
            <img src={require('./image/kanshu.png')} alt="免费试读" width='35' />
            <p style={{ color: '#ffffff' }}>免费试读</p>
          </div>
          <div className='details_bottom_add' onClick={this.escHome}>
            <img src={require('../image/zhuye.png')} alt="返回主页" width='35' />
            <p>返回主页</p>
          </div>
        </div>
      </div>
    )
  }
}